package mutilthread;

import java.util.concurrent.locks.Lock;

/**
 * Created with IntelliJ IDEA.
 * Description: 懒汉模式实现的单例模式
 * User: Li_yizYa
 * Date: 2025—03—26
 * Time: 20:40
 */
class SingletonLazy {
    //此处先把这个实例的引用设为空，先不着急创建实例
    private static volatile SingletonLazy instance = null;
    private static Object Locker = new Object();

    /**
     * 通过条件判断，在应该加锁的时候加锁，不需要加锁的时候直接跳过加锁
     * 该段代码可能会因为指令重排序，引起线程安全问题
     * @return
     */
    public static SingletonLazy getInstance() {
        //在这个条件中判定当前是否应该要加锁
        if (instance == null) { //判断是否要加锁
            synchronized (Locker) {
                if (instance == null) { //判断是否要创建 对象
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
    /**
     * 加锁解决了线程安全问题，但同样会带来阻塞问题
     * @return
     */
    public static SingletonLazy getInstance2() {
        synchronized (Locker) {
            if (instance == null) {
                instance = new SingletonLazy();
            }
        }
        return instance;
    }
    /**
     * 线程不安全的懒汉模式
     * @return
     */
    public static SingletonLazy getInstance1() {
        if (instance == null) {
            instance = new SingletonLazy();
        }

        return instance;
    }
    private SingletonLazy() {}
}
public class Demo14 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);
    }
}
